package org.openspml.providers.one_c.commands;

import java.util.Collections;
import java.util.List;

import org.openspml.message.FilterTerm;
import org.openspml.message.SearchRequest;
import org.openspml.message.SearchResponse;
import org.openspml.message.SearchResult;
import org.openspml.message.SpmlResponse;
import org.openspml.providers.one_c.api.connection.GlobalContext;
import org.openspml.providers.one_c.api.users.InfoBaseUser;
import org.openspml.providers.one_c.api.users.InfoBaseUsersManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Search request.
 * Now supports only search by "accountID-user name".
 * 
 * @author <A href="mailto:abashev at gmail dot com">Alexey Abashev</A>
 * @version $Id$
 */
public class SearchRequestCommand {
	private static final String ACCOUNT_ID = "accountId";
	private static final String FIRST_NAME = "gn";
	private static final String LAST_NAME = "sn";

	private final Logger log = LoggerFactory.getLogger(SearchRequestCommand.class);

	public SpmlResponse execute(GlobalContext context, SearchRequest request) {
		SearchResponse response = (SearchResponse) request.createResponse();
		@SuppressWarnings("unchecked")
		List<FilterTerm> terms = request.getFilter().getTerms();
		
		boolean supported = false;
		
		for (FilterTerm term : terms) {
			if (term.getName().equals(ACCOUNT_ID) && (term.getOperation().equals(FilterTerm.OP_EQUAL))) {
				supported = true;
				
				String name = (String) term.getValue();
				
				log.trace("Making search request by name [{}]", name);
				
				try {
					InfoBaseUsersManager manager = context.getInfoBaseUsers();
					InfoBaseUser user = manager.findByName(name);
					
					if (user != null) {
						log.trace("User with name [{}] was found", name);
						
						SearchResult result = new SearchResult();
						
						result.setIdentifier(name);
						
						@SuppressWarnings("unchecked")
						List<String> attributes = request.getAttributes();
						
						for (String n : attributes) {
							if (n.equals(FIRST_NAME)) {
								String fullName = user.getFullName();
								
								result.setAttribute(FIRST_NAME, fullName.substring(0, fullName.indexOf(' ')));
							} else if (n.equals(LAST_NAME)) {
								String fullName = user.getFullName();
								
								result.setAttribute(LAST_NAME, fullName.substring(fullName.indexOf(' ') + 1));
							} else {
								result.setAttribute(n, "");
							}
						}
						
						response.addResult(result);
						response.setResult(SpmlResponse.RESULT_SUCCESS);
					} else {
						log.trace("User with name [{}] not found", name);
						
						response.setResults(Collections.emptyList());
						response.setResult(SpmlResponse.RESULT_SUCCESS);
					}
				} catch (Exception e) {
					log.error("Unable to find user with name [" + name + "]", e);
					
			        response.setError(SpmlResponse.ERROR_CUSTOM_ERROR);
			        response.setErrorMessage(e);
				}
			}
		}
		
		if (!supported) {
	        response.setError(SpmlResponse.ERROR_UNSUPPORTED_OPERATION);
	        response.setErrorMessage("Filtering request is not supported");
		}
		
		return response;
	}
}
